{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "intro_to_modeling.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LY0SJUCSY305"
      },
      "source": [
        "#### Copyright 2018 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "8Q1hsKyBZDVu",
        "colab": {}
      },
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "y5tftaRtUcm7"
      },
      "source": [
        "#Intro to Modeling\n",
        "\n",
        "\n",
        "**Learning Objectives:**\n",
        "* Become familiar with pandas for handling small datasets\n",
        "* Use the tf.Estimator and Feature Column API to experiment with feature transformations\n",
        "* Use visualizations and run experiments to understand the value of feature transformations\n",
        "\n",
        "Please **make a copy** of this Colab notebook before starting this lab. To do so, choose **File**->**Save a copy in Drive**."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "TT_bZ9E0ZWaN"
      },
      "source": [
        "## Setup\n",
        "\n",
        "Let's start by importing our dependencies."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "wZ_T2SgDVKUH",
        "colab": {}
      },
      "source": [
        "%reset -f\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "import math\n",
        "\n",
        "import tensorflow.compat.v1 as tf\n",
        "tf.disable_v2_behavior()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Sx4-PWE-VaD_"
      },
      "source": [
        "## Pandas, a helpful data analysis library for in-memory dataset\n",
        "\n",
        "We use a package called [Pandas](http://pandas.pydata.org/) for reading in our data, exploring our data and doing some basic processing. It is really helpful for datasets that fit in memory! And it has some nice integrations, as you will see.\n",
        "\n",
        "First we set up some options to control how items are displayed and the maximum number of rows to show when displaying a table.  Feel free to change this setup to whatever you'd like."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "hKUIMcPCVRqv",
        "colab": {}
      },
      "source": [
        "# Set pandas output display to have one digit for decimal places and limit it to\n",
        "# printing 15 rows.\n",
        "pd.options.display.float_format = '{:.2f}'.format\n",
        "pd.options.display.max_rows = 15"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "H_fTMztUVelY"
      },
      "source": [
        "### Load the dataset with pandas\n",
        "The car data set we will be using in this lab is provided as a comma separated file without a header row.  In order for each column to have a meaningful header name we must provide it.  We get the information about the columns from the [Automobile Data Set](https://archive.ics.uci.edu/ml/datasets/automobile).\n",
        "\n",
        "We will use the features of the car, to try to predict its price.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "Y38V73EgVYwt",
        "colab": {}
      },
      "source": [
        "# Provide the names for the columns since the CSV file with the data does\n",
        "# not have a header row.\n",
        "feature_names = ['symboling', 'normalized-losses', 'make', 'fuel-type',\n",
        "        'aspiration', 'num-doors', 'body-style', 'drive-wheels',\n",
        "        'engine-location', 'wheel-base', 'length', 'width', 'height', 'weight',\n",
        "        'engine-type', 'num-cylinders', 'engine-size', 'fuel-system', 'bore',\n",
        "        'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg',\n",
        "        'highway-mpg', 'price']\n",
        "\n",
        "\n",
        "# Load in the data from a CSV file that is comma separated.\n",
        "car_data = pd.read_csv('https://storage.googleapis.com/mledu-datasets/cars_data.csv',\n",
        "                        sep=',', names=feature_names, header=None, encoding='latin-1')\n",
        "\n",
        "\n",
        "# We'll then randomize the data, just to be sure not to get any pathological\n",
        "# ordering effects that might harm the performance of Stochastic Gradient\n",
        "# Descent.\n",
        "car_data = car_data.reindex(np.random.permutation(car_data.index))\n",
        "\n",
        "print(\"Data set loaded. Num examples: \", len(car_data))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "nAHZBtDlkmGa"
      },
      "source": [
        "This is a really small dataset! Only 205 examples.\n",
        "\n",
        "For simplicity in this codelab, we do not split the data further into training and validation. But you MUST do this on real datasets, or else you will overfit to your single dataset."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "aQ1HxLrOVqZk"
      },
      "source": [
        "## Task 0: Use pandas to explore and prepare the data\n",
        "\n",
        "- Use Pandas to inspect the data and manually curate a list of numeric_feature_names and categorical_feature_names.\n",
        "\n",
        "\n",
        "Useful functions:\n",
        "- `type()` called on any Python object describes the type of the object\n",
        "- `dataframe[4:7]` pulls out rows 4, 5, 6 in a Pandas dataframe\n",
        "- `dataframe[['mycol1', 'mycol2']]` pulls out the two requested columns into a new Pandas dataframe\n",
        "- `dataframe['mycol1']` returns a Pandas series -- not a dataframe!\n",
        "- `dataframe.describe()` prints out statistics for each dataframe column"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "TfeHYeMf7PwQ",
        "colab": {}
      },
      "source": [
        "car_data[4:7]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "VsOUrVozoe9u",
        "colab": {}
      },
      "source": [
        "LABEL = 'price'\n",
        "\n",
        "numeric_feature_names = car_data[['symboling','normalized-losses','wheel-base','engine-size','bore','stroke','compression-ratio','horsepower','peak-rpm','city-mpg','highway-mpg','price']]\n",
        "categorical_feature_names = list(set(feature_names) - set(numeric_feature_names) - set([LABEL]))\n",
        "\n",
        "# The correct solution will pass these assert statements.\n",
        "assert len(numeric_feature_names) == 15\n",
        "assert len(categorical_feature_names) == 10"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "lLFkHgBm8O1Y",
        "colab": {}
      },
      "source": [
        "#@title Solution (to view code, from cell's menu, select Form -> Show Code)\n",
        "numeric_feature_names = ['symboling', 'normalized-losses', 'wheel-base',\n",
        "        'length', 'width', 'height', 'weight', 'engine-size', 'horsepower',\n",
        "        'peak-rpm', 'city-mpg', 'highway-mpg', 'bore', 'stroke',\n",
        "         'compression-ratio']\n",
        "\n",
        "categorical_feature_names = list(set(feature_names) - set(numeric_feature_names) - set([LABEL]))\n",
        "\n",
        "assert len(numeric_feature_names) == 15\n",
        "assert len(categorical_feature_names) == 10"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "nabeQFGBpDEN",
        "colab": {}
      },
      "source": [
        "# Run to inspect numeric features.\n",
        "car_data[numeric_feature_names]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "b1ss9Q7mpiBy",
        "colab": {}
      },
      "source": [
        "# Run to inspect categorical features.\n",
        "car_data[categorical_feature_names]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "6OjDegBgqNnu",
        "colab": {}
      },
      "source": [
        "# Coerce the numeric features to numbers. This is necessary because the model\n",
        "# crashes because not all the values are numeric.\n",
        "for feature_name in numeric_feature_names + [LABEL]:\n",
        "  car_data[feature_name] = pd.to_numeric(car_data[feature_name], errors='coerce')\n",
        "\n",
        "# Fill missing values with 0.\n",
        "# Is this an OK thing to do? You may want to come back and revisit this decision later.\n",
        "car_data.fillna(0, inplace=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Uq-t-8GPvnCW"
      },
      "source": [
        "## Task 1: Make your best model with numeric features. No normalization allowed.\n",
        "\n",
        "Modify the model provided below to achieve the lowest eval loss. You may want to change various hyperparameters:\n",
        "- learning rate\n",
        "- choice of optimizer\n",
        "- hidden layer dimensions -- make sure your choice here makes sense given the number of training examples\n",
        "- batch size\n",
        "- num training steps\n",
        "- (anything else you can think of changing)\n",
        "\n",
        "Do not use the `normalizer_fn` arg on `numeric_column`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "JH6KJp-4-E_Q",
        "colab": {}
      },
      "source": [
        "# This code \"works\", but because of bad hyperparameter choices it gets NaN loss\n",
        "# during training. Try fixing this.\n",
        "\n",
        "batch_size = 16\n",
        "\n",
        "print(numeric_feature_names)\n",
        "x_df = car_data[numeric_feature_names]\n",
        "y_series = car_data['price']\n",
        "\n",
        "# Create input_fn's so that the estimator knows how to read in your data.\n",
        "train_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    num_epochs=None,\n",
        "    shuffle=True)\n",
        "\n",
        "eval_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "# Feature columns allow the model to parse the data, perform common\n",
        "# preprocessing, and automatically generate an input layer for the tf.Estimator.\n",
        "model_feature_columns = [\n",
        "    tf.feature_column.numeric_column(feature_name) for feature_name in numeric_feature_names\n",
        "]\n",
        "print('model_feature_columns', model_feature_columns)\n",
        "\n",
        "est = tf.estimator.DNNRegressor(\n",
        "    feature_columns=model_feature_columns,\n",
        "    hidden_units=[64],\n",
        "    optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01),\n",
        "  )\n",
        "\n",
        "# TRAIN\n",
        "num_print_statements = 10\n",
        "num_training_steps = 10000\n",
        "for _ in range(num_print_statements):\n",
        "  est.train(train_input_fn, steps=num_training_steps // num_print_statements)\n",
        "  scores = est.evaluate(eval_input_fn)\n",
        "  \n",
        "  # The `scores` dictionary has several metrics automatically generated by the\n",
        "  # canned Estimator.\n",
        "  # `average_loss` is the average loss for an individual example.\n",
        "  # `loss` is the summed loss for the batch.\n",
        "  # In addition to these scalar losses, you may find the visualization functions\n",
        "  # in the next cell helpful for debugging model quality.\n",
        "  print('scores', scores)\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "3ptcfj_9Xi9M",
        "colab": {}
      },
      "source": [
        "#@title Possible solution\n",
        "# Here is one possible solution:\n",
        "# The only necessary change to fix the NaN training loss was the choice of optimizer.\n",
        "\n",
        "# Changing other parameters could improve model quality, but take it with a\n",
        "# grain of salt. The dataset is very small.\n",
        "\n",
        "batch_size = 16\n",
        "\n",
        "print(numeric_feature_names)\n",
        "x_df = car_data[numeric_feature_names]\n",
        "y_series = car_data['price']\n",
        "\n",
        "train_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    num_epochs=None,\n",
        "    shuffle=True)\n",
        "\n",
        "eval_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "# Feature columns allow the model to parse the data, perform common\n",
        "# preprocessing, and automatically generate an input layer for the tf.Estimator.\n",
        "model_feature_columns = [\n",
        "    tf.feature_column.numeric_column(feature_name) for feature_name in numeric_feature_names\n",
        "]\n",
        "print('model_feature_columns', model_feature_columns)\n",
        "\n",
        "est = tf.estimator.DNNRegressor(\n",
        "    feature_columns=model_feature_columns,\n",
        "    hidden_units=[64],\n",
        "    optimizer=tf.train.AdagradOptimizer(learning_rate=0.01),\n",
        "  )\n",
        "\n",
        "# TRAIN\n",
        "num_print_statements = 10\n",
        "num_training_steps = 10000\n",
        "for _ in range(num_print_statements):\n",
        "  est.train(train_input_fn, steps=num_training_steps // num_print_statements)\n",
        "  scores = est.evaluate(eval_input_fn)\n",
        "  \n",
        "  # The `scores` dictionary has several metrics automatically generated by the \n",
        "  # canned Estimator.\n",
        "  # `average_loss` is the average loss for an individual example.\n",
        "  # `loss` is the summed loss for the batch.\n",
        "  # In addition to these scalar losses, you may find the visualization functions\n",
        "  # in the next cell helpful for debugging model quality.\n",
        "  print('scores', scores)\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Rxto3DwsjYw4"
      },
      "source": [
        "### Visualize your model's predictions\n",
        "\n",
        "After you have a trained model, it may be helpful to understand how your model's inference differs from the actual data.\n",
        "\n",
        "This helper function `scatter_plot_inference` does that for you. Real data is in grey. Your model's predictions are in orange.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "uGSXwX2fju1N",
        "colab": {}
      },
      "source": [
        "from matplotlib import pyplot as plt\n",
        "\n",
        "\n",
        "def scatter_plot_inference_grid(est, x_df, feature_names):\n",
        "  \"\"\"Plots the predictions of the model against each feature.\n",
        "  \n",
        "  Args:\n",
        "    est: The trained tf.Estimator.\n",
        "    x_df: The pandas dataframe with the input data (used to create\n",
        "      predict_input_fn).\n",
        "    feature_names: An iterable of string feature names to plot.\n",
        "  \"\"\"\n",
        "  def scatter_plot_inference(axis,\n",
        "                             x_axis_feature_name,\n",
        "                             y_axis_feature_name,\n",
        "                             predictions):\n",
        "    \"\"\"Generate one subplot.\"\"\"\n",
        "    # Plot the real data in grey.\n",
        "    y_axis_feature_name = 'price'\n",
        "    axis.set_ylabel(y_axis_feature_name)\n",
        "    axis.set_xlabel(x_axis_feature_name)\n",
        "    axis.scatter(car_data[x_axis_feature_name],\n",
        "                 car_data[y_axis_feature_name],\n",
        "                 c='grey')\n",
        "\n",
        "    # Plot the predicted data in orange.\n",
        "    axis.scatter(car_data[x_axis_feature_name], predictions, c='orange')\n",
        "\n",
        "  predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "  predictions = [\n",
        "    x['predictions'][0]\n",
        "    for x in est.predict(predict_input_fn)\n",
        "  ]\n",
        "  \n",
        "  num_cols = 3\n",
        "  num_rows = int(math.ceil(len(feature_names)/float(num_cols)))\n",
        "  f, axarr = plt.subplots(num_rows, num_cols)\n",
        "  size = 4.5\n",
        "  f.set_size_inches(num_cols*size, num_rows*size)\n",
        "  \n",
        "  for i, feature_name in enumerate(numeric_feature_names):\n",
        "    axis = axarr[int(i/num_cols), i%num_cols]\n",
        "    scatter_plot_inference(axis, feature_name, 'price', predictions)\n",
        "  plt.show()\n",
        "\n",
        "scatter_plot_inference_grid(est, x_df, numeric_feature_names)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "uBZI8f_8Yfph"
      },
      "source": [
        "## Task 2: Take your best numeric model from earlier. Add normalization.\n",
        "\n",
        "### Add normalization to your best numeric model from earlier\n",
        "\n",
        "- You decide what type of normalization to add, and for which features\n",
        "- You will need to use the `normalizer_fn` arg on [`numeric_column`](https://g3doc.corp.google.com/learning/brain/public/g3doc/api_docs/python/tf/feature_column/numeric_column.md?cl=head)\n",
        "    - An example of a silly normalizer_fn that shifts inputs down by 1, and then negates the value:\n",
        "    \n",
        "         normalizer_fn = lambda x: tf.neg(tf.subtract(x, 1))\n",
        "\n",
        "- You may find these pandas functions helpful:\n",
        "    - dataframe.mean()['your_feature_name']\n",
        "    - dataframe.std()['your_feature_name']\n",
        "- You will need to retune the hyperparameters from earlier.\n",
        "\n",
        "\n",
        "**Does normalization improve model quality on this dataset? Why or why not?**"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "jY_C_QgcZg1-",
        "colab": {}
      },
      "source": [
        "# This 1D visualization of each numeric feature might inform your normalization\n",
        "# decisions.\n",
        "for feature_name in numeric_feature_names:\n",
        "  car_data.hist(column=feature_name)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "oiEpDZKSj8pN"
      },
      "source": [
        "###Train your model with numeric features + normalization"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "c30Y6IiR8iVn",
        "colab": {}
      },
      "source": [
        "## Your code goes here"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "RxYJy71zaZsy",
        "colab": {}
      },
      "source": [
        "#@title Possible solution\n",
        "# This does Z-score normalization since the distributions for most features looked\n",
        "# roughly normally distributed.\n",
        "\n",
        "# Z-score normalization subtracts the mean and divides by the standard deviation,\n",
        "# to give a roughly standard normal distribution (mean = 0, std = 1) under a\n",
        "# normal distribution assumption. Epsilon prevents divide by zero.\n",
        "\n",
        "# With normalization, are you able to get the model working with\n",
        "# GradientDescentOptimizer? Z-score normalization doesn't seem to be able to get\n",
        "# SGD working. Maybe a different type of normalization would?\n",
        "\n",
        "batch_size = 16\n",
        "\n",
        "print(numeric_feature_names)\n",
        "x_df = car_data[numeric_feature_names]\n",
        "y_series = car_data['price']\n",
        "\n",
        "train_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    num_epochs=None,\n",
        "    shuffle=True)\n",
        "\n",
        "eval_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "# Epsilon prevents divide by zero.\n",
        "epsilon = 0.000001\n",
        "model_feature_columns = [\n",
        "    tf.feature_column.numeric_column(feature_name,\n",
        "                                     normalizer_fn=lambda val: (val - x_df.mean()[feature_name]) / (epsilon + x_df.std()[feature_name]))\n",
        "    for feature_name in numeric_feature_names\n",
        "]\n",
        "print('model_feature_columns', model_feature_columns)\n",
        "\n",
        "est = tf.estimator.DNNRegressor(\n",
        "    feature_columns=model_feature_columns,\n",
        "    hidden_units=[64],\n",
        "    optimizer=tf.train.AdagradOptimizer(learning_rate=0.01),\n",
        "  )\n",
        "\n",
        "# TRAIN\n",
        "num_print_statements = 10\n",
        "num_training_steps = 10000\n",
        "for _ in range(num_print_statements):\n",
        "  est.train(train_input_fn, steps=num_training_steps // num_print_statements)\n",
        "  scores = est.evaluate(eval_input_fn)\n",
        "  \n",
        "  # The `scores` dictionary has several metrics automatically generated by the \n",
        "  # canned Estimator.\n",
        "  # `average_loss` is the average loss for an individual example.\n",
        "  # `loss` is the summed loss for the batch.\n",
        "  # In addition to these scalar losses, you may find the visualization functions\n",
        "  # in the next cell helpful for debugging model quality.\n",
        "  print('scores', scores)\n",
        "\n",
        "scatter_plot_inference_grid(est, x_df, numeric_feature_names)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "fruh0Qj5_Bos"
      },
      "source": [
        "## Task 3: Make your best model using only categorical features\n",
        "\n",
        "- Look at the possible feature columns for categorical features. They begin with `categorical_column_with_` in go/tf-ops.\n",
        "- You may find `dataframe[categorical_feature_names].unique()` helpful.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "-udhHnNS2WvN",
        "colab": {}
      },
      "source": [
        "## Your code goes here"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "EftIzPAI9RJj",
        "colab": {}
      },
      "source": [
        "#@title Possible solution\n",
        "# We have the full list of values that each feature takes on, and the list is\n",
        "# relatively small so we use categorical_column_with_vocabulary_list.\n",
        "\n",
        "batch_size = 16\n",
        "\n",
        "x_df = car_data[categorical_feature_names]\n",
        "y_series = car_data['price']\n",
        "\n",
        "train_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    num_epochs=None,\n",
        "    shuffle=True)\n",
        "\n",
        "eval_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "model_feature_columns = [\n",
        "    tf.feature_column.indicator_column(\n",
        "        tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "            feature_name, vocabulary_list=car_data[feature_name].unique()))\n",
        "    for feature_name in categorical_feature_names\n",
        "]\n",
        "print('model_feature_columns', model_feature_columns)\n",
        "\n",
        "est = tf.estimator.DNNRegressor(\n",
        "    feature_columns=model_feature_columns,\n",
        "    hidden_units=[64],\n",
        "    optimizer=tf.train.AdagradOptimizer(learning_rate=0.01),\n",
        "  )\n",
        "\n",
        "# TRAIN\n",
        "num_print_statements = 10\n",
        "num_training_steps = 10000\n",
        "for _ in range(num_print_statements):\n",
        "  est.train(train_input_fn, steps=num_training_steps // num_print_statements)\n",
        "  scores = est.evaluate(eval_input_fn)\n",
        "  \n",
        "  # The `scores` dictionary has several metrics automatically generated by the\n",
        "  # canned Estimator.\n",
        "  # `average_loss` is the average loss for an individual example.\n",
        "  # `loss` is the summed loss for the batch.\n",
        "  # In addition to these scalar losses, you may find the visualization functions\n",
        "  # in the next cell helpful for debugging model quality.\n",
        "  print('scores', scores)\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "gyBH5Wai_HTD"
      },
      "source": [
        "## Task 4: Using all the features, make the best model that you can make\n",
        "\n",
        "With all the features combined, your model should perform better than your earlier models using numerical and categorical models alone. Tune your model until that is the case."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "JNfCzC-q8edv",
        "colab": {}
      },
      "source": [
        "## Your code goes here"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "CmaGHWFVGKMr",
        "colab": {}
      },
      "source": [
        "#@title Possible solution\n",
        "# This is a first pass at a model that uses all the features.\n",
        "# Do you have any improvements?\n",
        "\n",
        "batch_size = 16\n",
        "\n",
        "x_df = car_data[numeric_feature_names + categorical_feature_names]\n",
        "y_series = car_data['price']\n",
        "\n",
        "train_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    num_epochs=None,\n",
        "    shuffle=True)\n",
        "\n",
        "eval_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    y=y_series,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "predict_input_fn = tf.estimator.inputs.pandas_input_fn(\n",
        "    x=x_df,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False)\n",
        "\n",
        "epsilon = 0.000001\n",
        "model_feature_columns = [\n",
        "    tf.feature_column.indicator_column(\n",
        "        tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "            feature_name, vocabulary_list=car_data[feature_name].unique()))\n",
        "    for feature_name in categorical_feature_names\n",
        "] + [\n",
        "    tf.feature_column.numeric_column(feature_name,\n",
        "                                     normalizer_fn=lambda val: (val - x_df.mean()[feature_name]) / (epsilon + x_df.std()[feature_name]))\n",
        "    for feature_name in numeric_feature_names\n",
        "]\n",
        "\n",
        "\n",
        "print('model_feature_columns', model_feature_columns)\n",
        "\n",
        "est = tf.estimator.DNNRegressor(\n",
        "    feature_columns=model_feature_columns,\n",
        "    hidden_units=[64],\n",
        "    optimizer=tf.train.AdagradOptimizer(learning_rate=0.01),\n",
        "  )\n",
        "\n",
        "# TRAIN\n",
        "num_print_statements = 10\n",
        "num_training_steps = 10000\n",
        "for _ in range(num_print_statements):\n",
        "  est.train(train_input_fn, steps=num_training_steps // num_print_statements)\n",
        "  scores = est.evaluate(eval_input_fn)\n",
        "  \n",
        "  # The `scores` dictionary has several metrics automatically generated by the \n",
        "  # canned Estimator.\n",
        "  # `average_loss` is the average loss for an individual example.\n",
        "  # `loss` is the summed loss for the batch.\n",
        "  # In addition to these scalar losses, you may find the visualization functions\n",
        "  # in the next cell helpful for debugging model quality.\n",
        "  print('scores', scores)\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}